﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HomeWork10
{
    public partial class Form1 : Form
    {
        private delegate void MyDelegate();
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string engine1 = "baidu";
            string engine2 = "bing";
            try { 
            Task baidu = new Task(() => { Search("https://www.baidu.com/baidu?wd=" + textBox1.Text, textBox2, engine1); });
            Task bing = new Task(() => { Search("https://cn.bing.com/search?q=" + textBox1.Text, textBox3, engine2); });
            baidu.Start();
            bing.Start(); }
            catch (Exception exp) {
                textBox2.Text = "error!";
                textBox3.Text = "error!";
            }

        }
        private void Search(string url, TextBox textBox, string engine)
        {

          if (engine == "bing"){ 
                HtmlWeb web = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument doc = web.Load(url);
                HtmlNode hNode = doc.DocumentNode.SelectSingleNode("//*[@id='b_results']");
                HtmlNodeCollection hnc = hNode.ChildNodes;
                string result = null;
                foreach (var node in hnc)
                {
                    result +=node.InnerText;
                }
                textBox.Text=result;
          }

           if (engine == "baidu") { 
                HtmlWeb web = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument doc = web.Load(url);
                HtmlNodeCollection hnc = doc.DocumentNode.SelectNodes("//div[@class='result c-container xpath-log new-pmd']");
                string result = null;
                foreach (var node in hnc)
                {
                    result += node.InnerText;
                }
                textBox.Text=result;
           }

        }
    }
}
